#coding=utf-8
#Boa:Dialog:DlgFundCustomer

import wx

import DlgCustomerChoice
import DlgPopupSupplier


from MyListCtrl import MyFundCustmoerListCtrl
from ctrlAider import *
from product import *

def create(parent):
    return DlgFundCustomer(parent)

[wxID_DLGFUNDCUSTOMER, wxID_DLGFUNDCUSTOMERBTNSEARCH, 
 wxID_DLGFUNDCUSTOMERTCCUSTOMER, wxID_DLGFUNDCUSTOMERTCSTAT, 
 wxID_DLGFUNDCUSTOMERTCUSTOMER, 
] = [wx.NewId() for _init_ctrls in range(5)]

[Type_Customer, Type_Supplier] = [i for i in range(2)]

class DlgFundCustomer(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DLGFUNDCUSTOMER,
              name=u'DlgFundCustomer', parent=prnt, pos=wx.Point(324, 120),
              size=wx.Size(956, 650), style=wx.DEFAULT_DIALOG_STYLE,
              title=u'\u5ba2\u6237\u8d26\u52a1\u5f80\u6765')
        self.SetClientSize(wx.Size(948, 616))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))
        self.Center(wx.BOTH)

        self.tPeer = wx.StaticText(id=wxID_DLGFUNDCUSTOMERTCUSTOMER,
              label=u'\u5ba2\u6237\u540d\u79f0\uff1a', name=u'tPeer',
              parent=self, pos=wx.Point(30, 32), size=wx.Size(90, 24), style=0)

        self.tcPeerName = wx.TextCtrl(id=wxID_DLGFUNDCUSTOMERTCCUSTOMER,
              name=u'tcPeerName', parent=self, pos=wx.Point(120, 32),
              size=wx.Size(160, 22), style=0, value=u'')
        self.tcPeerName.Bind(wx.EVT_TEXT, self.OnTcCustomerText,
              id=wxID_DLGFUNDCUSTOMERTCCUSTOMER)

        self.btnSearch = wx.Button(id=wxID_DLGFUNDCUSTOMERBTNSEARCH,
              label=u'\u67e5\u627e', name=u'btnSearch', parent=self,
              pos=wx.Point(296, 32), size=wx.Size(72, 24), style=0)
        self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton,
              id=wxID_DLGFUNDCUSTOMERBTNSEARCH)

        self.tcStat = wx.TextCtrl(id=wxID_DLGFUNDCUSTOMERTCSTAT, name=u'tcStat',
              parent=self, pos=wx.Point(34, 63), size=wx.Size(768, 73),
              style=wx.RAISED_BORDER | wx.TE_MULTILINE, value=u'')

    def __init__(self, parent, type=Type_Customer):
        self._init_ctrls(parent)

        self.myInit(type)
        
    def myInit(self, type):
        self.m_peer = None
        
        if(type == Type_Customer):
            self.popupWin = DlgCustomerChoice.create(self)
            self.lc = MyFundCustmoerListCtrl(self)
            
        elif(type == Type_Supplier):
            self.popupWin = DlgPopupSupplier.create(self)
            self.lc = MyFundCustmoerListCtrl(self, type=MyFundCustmoerListCtrl.Type_Supplier)
        
        
        #self.tcCust = MyTextCtrlDecorator(self.tcPeer, self.popupWin)
        #self.tcCust.ChangeValue(u'全部客户')
        self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)
        
        self.lc.SetSize(wx.Size(850, 400))
        self.lc.Move(wx.Point(30,140))
        
        #初始化时不进行数据装载，以免影响速度
        #self.lc.refresh()
        #self.refreshStat()

    def refreshStat(self):
        str = u'总销售单数：%d  总收款单数：%d\n'\
                u'销售总金额：%.2f  收款总金额：%.2f  优惠总金额：%.2f\n'\
                u'欠款总金额：%.2f'\
                %(self.lc.m_saleCnt, self.lc.m_voucherCnt,
                 self.lc.m_total, self.lc.m_paid, self.lc.m_discount,
                 self.lc.m_total - self.lc.m_paid - self.lc.m_discount)
        
        self.tcStat.SetValue(str)

    def setBtnAccount(self, money):
        self.btnLink = wx.Button(self)
        self.btnLink.SetLabel(u'关联到选中销售单')
        self.btnLink.SetSize(self.btnLink.GetBestSize())
        self.btnLink.Move((400, 32))
        self.btnLink.Bind(wx.EVT_BUTTON, self.OnBtnLinkButton)
    
        self.amount = money
        
    def getLinkVoucherId(self):
        return self.linkVoucherId 
    
    def setSelectObj(self, obj):
        '''设置选中客户'''
        if (obj is not None):
            #if None, we keep old value
            self.m_peer = obj
            
        if (self.m_peer is not None):
            name = self.m_peer.getValue(self.m_peer.COL_NAME)
        else:
            name = ''
            
        self.tcPeer.ChangeValue(name)
    
    def setSelectPeer(self, obj):
        self.setSelectObj(obj)
        
    def setCustomer(self, obj):
        '''设置选中客户'''
        if (obj is not None):
            #if None, we keep old value
            self.m_peer = obj
            
        if (self.m_peer is not None):
            name = self.m_peer.getValue(self.m_peer.COL_NAME)
        else:
            name = ''
            
        self.tcPeer.ChangeValue(name)

    def getPopupWinPos(self):
        posBtn = self.tcPeer.ClientToScreen((0,0))
        posPrt = self.ClientToScreen((0,0))
        sz =  self.tcPeer.GetSize()
        return (posPrt.x, posBtn.y + sz.GetHeight())
    
    def refresh(self):
        filter = {}
        if self.m_peer is not None:
            filter['peerId'] = self.m_peer.getValue(self.m_peer.COL_ID)
      
        cnt = self.lc.refresh(filter)
        
        self.refreshStat()
    
    def OnBtnLinkButton(self, event):
        '''设置收款单与账户变动的关系'''
        obj = self.lc.getSelectedVoucher()
        if (obj is None):
            msg = u'请选择收款单，没有符合需要的收款单，请新建一个'
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        if (self.amount != obj.getValue(obj.COL_MONEY)):
            msg = u'账户变动金额%d与收款单金额不匹配，请重新选择收款单' %self.amount
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        self.linkVoucherId = obj.getValue(obj.COL_ID)
        self.EndModal(wx.ID_OK)
        
    def OnBtnSearchButton(self, event):
        if self.tcPeer.GetValue() == '':
            #self.tcPeer.ChangeValue(u'全部客户')
            self.m_peer = None
        
        self.refresh()

    def OnTcCustomerText(self, event):
        self.tcPeer.SetFocus()

        str = self.tcPeer.GetValue()
        self.popupWin.setFilter(str)

        if not self.popupWin.IsShown():
            print 'first show popupWin'
            #self.popupWin.Popup(self.getPopupWinPos())
            self.popupWin.Show()
            #self.popupWinShown = True
            print 'tcPeer.SetFocus'
            #import time
            #time.sleep(1)
            #有可能是虽然执行了Show()但是子窗口只是发送了事件，而没有真正显示
            #当子窗口实际现实的时候，又会导致KillFocus？？
            self.tcPeer.SetFocus()

    def OnTcCustomerKillFocus(self, event):
        '''自动Dismiss太麻烦了，foucs总是出问题，所以以后执行手动退出，该函数作废'''
        print 'OnTCCustomerKillFocus'
        print 'active %d' %self.popupWin.IsActive()
        print 'focus %s' %self.FindFocus()
        print 'new %s' %event.GetWindow()
        
        if (not self.popupWin.IsActive()) and event.GetWindow() is not None:
            self.popupWin.Dismiss()

        
    
        
